﻿#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Taxonomy.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Runtime.dll"

#load "Client.fs"

open Client
open Microsoft.SharePoint.Client
open Microsoft.SharePoint.Client.Application
open Microsoft.SharePoint.Client.Taxonomy
open System.Security;
open System

// =======================================================
// Work with Taxonomy Services
// =======================================================

let web = Client.Context.Web
Client.Load web
let list = web.Lists.GetByTitle("Documents")

let session = TaxonomySession.GetTaxonomySession(Client.Context)
let stores = session.TermStores
Client.Load stores

let store = stores.GetByName("Connection to: Managed Metadata Service Application")
Client.Load store

let group = store.Groups.GetByName("MyTermGroup")
Client.Load group

let set = group.TermSets.GetByName("MyTermSet");
Client.Load set
let msg = set.Name + " | " + set.Id.ToString()
printfn "%s\n" msg

// Get Term Group that is associated with site
let siteGroup = store.GetSiteCollectionGroup(Client.Context.Site, true)
Client.Load siteGroup.TermSets

printfn "%s\n" siteGroup.Name

// Set owner for Term Sets
for set in siteGroup.TermSets do
    Client.Load set
    set.Owner <- "me@geek.onmicrosoft.com"
    printfn "%s\n" set.Name


// Create new Term Set
let siteSet = siteGroup.CreateTermSet("MyKeyword", Guid.NewGuid(), 1033)
Client.ExecuteQuery()

Client.Load siteSet

// Update TermSet
siteSet.IsOpenForTermCreation <- true
Client.ExecuteQuery()

// Create Taxonnomy column
let fldx = web.Fields.AddFieldAsXml(@"<Field Name=""MyKeyword"" StaticName=""MyKeyword"" DisplayName=""MyKeyword"" ShowField=""Term1033""
    Description=""ILM Keyword"" Type='TaxonomyFieldType' Required=""TRUE"" Group=""My Columns"" FillInChoice=""TRUE"" ></Field>", false, AddFieldOptions.DefaultValue)
Client.Context.Web.Update()
Client.ExecuteQuery()

let fld = list.Fields.GetByTitle("MyKeyword");
Client.Load fld

fld.SchemaXml

Client.Load set.TermStore

let taxfld = Client.Context.CastTo<TaxonomyField>(fld)
Client.ExecuteQuery()

taxfld.Open <- true
taxfld.Update()
Client.ExecuteQuery()

taxfld.SspId <- set.TermStore.Id
taxfld.TermSetId <- set.Id
taxfld.Update()
Client.Context.Web.Update()
Client.ExecuteQuery()

// Work with Taxonomy fields
let item = list.GetItemById(16)
Client.Load item

let templateValue = item.["MyKeyword"] :?> TaxonomyFieldValue 

let tempTerm = session.GetTerm(Guid.Parse(templateValue.TermGuid))
Client.Load tempTerm